<template>
  <div class="app-container.home">
    <!-- 新增工厂按钮 -->
    <el-button type="primary" @click="showAddFactoryDialog">新增工厂</el-button>

    <!-- 新增工厂的弹出框 -->
    <el-dialog
      title="新增工厂"
      :visible.sync="addFactoryDialogVisible"
      width="30%"
    >
      <el-form ref="factoryForm" :model="factoryForm" label-width="80px">
        <el-form-item label="工厂名称">
          <el-input v-model="factoryForm.factoryName" placeholder="请输入工厂名称"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAddFactory">取消</el-button>
        <el-button type="primary" @click="confirmAddFactory">确定</el-button>
      </span>
    </el-dialog>

    <!-- 动态渲染工厂页面 -->
    <div v-for="(factory, index) in factories" :key="factory.name" class="factory-container">
      <h2>{{ factory.name }}</h2>
      <el-button type="danger" @click="showDelFactoryDialog(factory, index)">删除工厂</el-button>
      <!-- 在这里可以添加更多工厂相关的操作或内容 -->
    </div>
    <el-dialog
      title="删除工厂"
      :visible.sync="delFactoryDialogVisible"
      width="30%"
    >
    <span>是否确认要删除{{currentFactory}}?</span>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="removeFactory(currentIndex)">确 定</el-button>
        <el-button @click="delFactoryDialogVisible = false;">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addMenu, listMenu, delMenu, delMenuBatch} from '@/api/system/menu';
import pinyin from 'js-pinyin';

export default {
  name: 'Home',
  data() {
    return {
      // 控制弹出框的显示状态
      addFactoryDialogVisible: false,
      //删除弹窗
      delFactoryDialogVisible:false,
      currentFactory: null,   // 当前要删的工厂对象
      currentIndex: -1,        // 对应下标
      // 表单数据
      factoryForm: {
        factoryName: '' // 工厂名称
      },
      // 存储工厂信息
      factories: [],
      menuId:'',
      menuChildrenIds: []
    };
  },
  created() {
    this.loadFactory2022();
  },

  methods: {
    // 显示新增工厂的弹出框
    showAddFactoryDialog() {
      this.addFactoryDialogVisible = true;
    },
    // 取消新增工厂
    cancelAddFactory() {
      this.addFactoryDialogVisible = false;
      this.factoryForm.factoryName = ''; // 清空输入框
    },
    //删除弹窗
    showDelFactoryDialog(factory, index){
      this.delFactoryDialogVisible = true;
      this.currentFactory = factory.name;  // 当前要删的工厂对象
      this.currentIndex = index        // 对应下标
    },
    //获取工厂下的工厂名单
    loadFactory2022() {
      listMenu().then(res => {
        const nodes = res.data.filter(item => item.parentId === 2022);
        this.factories = nodes.filter(n => n.menuName !== '总览').map(n => ({ name: n.menuName }));
        if (!this.factories.length) console.warn('未找到工厂下的数据');
      }).catch(err => {
        this.$modal.msgError('获取菜单失败：' + err.msg);
      });
    },
    //新增工厂
    confirmAddFactory() {
      const factoryName = this.factoryForm.factoryName.trim();
      if (!factoryName) {
        this.$message.error('工厂名称不能为空！');
        return;
      }
      if (this.factories.some(f => f.name === factoryName)) {
        this.$message.error('工厂名称已存在！');
        return;
      }

      /* 1. 转拼音 */
      pinyin.setOptions({checkPolyphone: false, charCase: 0});
      const factoryNamePinyin = pinyin.getFullChars(factoryName)
        .replace(/\b(\w)/g, s => s.toUpperCase())

      /* 2. 组装菜单数据 */
      const dirData =  {
        parentId: 2022,
        menuName: factoryName,
        icon: 'table',
        menuType: 'M',
        orderNum: 2,
        isFrame: '1',
        isCache: '0',
        visible: '0',
        status: '0',
        path: `${factoryNamePinyin}`,
      };

      /* 3. 直接新增菜单 */
      addMenu(dirData).then(res => {
        const dirId = res.data;
        const pageData = {
          parentId: dirId,
          menuName: '总览',
          icon: 'table',
          menuType: 'C',
          orderNum: 1,
          isFrame: '1',
          isCache: '0',
          visible: '0',
          status: '0',
          path: `ZongLan`,
          component: 'Factory/Base/overview_index'
        }
        return addMenu(pageData);
      }).then(() => {
        // 3-1. 本地 factories 列表也推一条
        this.factories.push({name: factoryName});

        // 3-2. 关闭弹窗 & 清空
        this.addFactoryDialogVisible = false;
        this.factoryForm.factoryName = '';

        // 3-3. 提示
        this.$modal.msgSuccess('工厂与菜单均新增成功');
        // 当前页完整重载
        location.reload()
      }).catch(err => {
          this.$modal.msgError('新增菜单失败：' + err.msg);
      });
    },
    // 删除工厂
    removeFactory(index) {
      listMenu().then(res => {
        const item = res.data.find(m => m.menuType === 'M' && m.menuName.replace(/"/g, '') === this.factories[index].name);
        const itemChildrenS = res.data.filter(m => m.menuType === 'C' && m.parentId === item.menuId);
        this.menuId = item.menuId;
        this.menuChildrenIds = itemChildrenS.map(n => n.menuId);
        delMenuBatch(this.menuChildrenIds).then(() => {
          delMenu(this.menuId).then(()=>{
            this.factories.splice(index, 1);
            // 当前页完整重载
            location.reload()
          })
        })
      })
      this.delFactoryDialogVisible = false;
    }
  }
};
</script>

<style scoped>
.factory-container {
  margin-top: 20px;
  border: 1px solid #ccc;
  padding: 10px;
  width: 100%;
  box-sizing: border-box;
}
</style>
